const net = require('net')

// 找到可用的端口
const findAvailablePort = async (port, portAvailableCallback) => {
    function portUsed(port) {
        return new Promise((resolve, reject) => {
            const server = net.createServer().listen(port)
            server.on('listening', () => {
                server.close()
                resolve(port)
            })
            server.on('error', err => {
                if (err.code == 'EADDRINUSE') {
                    resolve(err)
                }
            })
        })
    }

    const res = await portUsed(port)
    if (res instanceof Error) {
        console.log(`端口：${port}被占用\n`)
        port++
        findAvailablePort(port, portAvailableCallback)
    } else {
        portAvailableCallback(port)
    }
}



module.exports = { findAvailablePort }